package da.metricscraft.client.threads;

import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.NodeList;


public class SpatialXMLLoader extends XMLLoader<HashMap<String, ArrayList<SpatialXMLLoader.LocationStruct>>> {

	private HashMap<String, ArrayList<SpatialXMLLoader.LocationStruct>> list = new HashMap<String, ArrayList<SpatialXMLLoader.LocationStruct>>();
	public SpatialXMLLoader(LoaderTypes type) {
		super(type);
		// TODO Auto-generated constructor stub
	}

	public enum MoveActions{
		MINE,
		MINE_FINE,
		DIE,
		TAKE_DAMAGE,
		KILL,
		BUILD,
		CRAFT,
		MOVE,
		NONE,
		DEVELOP
	}
	
	public class LocationStruct implements Comparable<LocationStruct>{
		private MoveActions action;
		private int lifetime;
		private Point position;

		public LocationStruct(int lifetime, Point position, MoveActions action){
			this.action = action;
			this.lifetime = lifetime;
			this.position = position;
		}

		public MoveActions getAction() {
			return action;
		}

		public int getLifetime() {
			return lifetime;
		}

		public Point getPosition() {
			return position;
		}

		@Override
		public int compareTo(LocationStruct arg0) {
			// TODO Auto-generated method stub
			return (lifetime < arg0.getLifetime())?-1:(lifetime == arg0.getLifetime())?0:1;
		}
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true){
			if (path != ""){
				readXML();
				NodeList playerList = xmldoc.getElementsByTagName("player");
				for (int j = 0; j < playerList.getLength(); j++){
					NodeList nl = playerList.item(j).getChildNodes();
					ArrayList<SpatialXMLLoader.LocationStruct> pointsOfThisPlayer = new ArrayList<SpatialXMLLoader.LocationStruct>();
					for(int i = 0; i < nl.getLength(); i++){
						
						NamedNodeMap attr = nl.item(i).getAttributes();
						int x = Integer.parseInt(attr.getNamedItem("x").getTextContent());
						int z = Integer.parseInt(attr.getNamedItem("z").getTextContent());
						pointsOfThisPlayer.add(new LocationStruct(Integer.parseInt(attr.getNamedItem("lifetime").getTextContent()), new Point(x, z), 
								MoveActions.valueOf(nl.item(i).getNodeName())));
					}
					list.put(playerList.item(j).getAttributes().getNamedItem("name").getTextContent(), pointsOfThisPlayer);
				}
				data = list;
				dispatch();
				
				path = "";
			}else{
				try {
					synchronized(this){
						this.wait();
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
